package com.cj.mobile.iabp.mvp.presenter;

import static com.cj.mobile.iabp.BuildConfig.AUTO_UPDATES;
import static com.cj.mobile.iabp.BuildConfig.IS_DEBUG_DATA;

import android.os.Bundle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.blankj.utilcode.util.RegexUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.global.AccountManager;
import com.cj.mobile.iabp.app.utils.RxUtils;
import com.cj.mobile.iabp.mvp.contract.LoginContract;
import com.cj.mobile.iabp.mvp.model.entity.AccountInfo;
import com.cj.mobile.iabp.mvp.model.entity.AppUpdate;
import com.jess.arms.cj.CommonResponse;
import com.cj.mobile.iabp.mvp.model.entity.LoginResponse;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    AccountManager accountManager;

    /**
     * 获取手机验证码倒计时时间(秒)
     */
    private final int mobileCheckCodeTime = 60;// 1分钟

    /**
     * 当前状态是否是首次启动登录
     */
    private Boolean isStartLogin = true;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    /**
     * 获取传进来的值
     */
    public void getBundleValues(Bundle bundle) {
        if (bundle != null) {
            isStartLogin = bundle.getBoolean("isStartLogin", true);
//            isMsgOpen = bundle.getBoolean(IS_MSG_OPEN, false);
        }
    }

    /**
     * 初始化默认值
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {

        if (IS_DEBUG_DATA) {
            mRootView.setUsernName("15032134297");
            mRootView.setPassword("123456");
        } else {
            mRootView.setUsernName(accountManager.getAccount());
            mRootView.setPassword(accountManager.getPassword());
        }

        //APP升级更新
        if (AUTO_UPDATES && isStartLogin)
            checkUpdateManager();
    }


    /**
     * 点击登录按钮
     */
    public void btnLoginOnClick(String username, String password, boolean mSwitchLogin) {
//        测试Bugly上报
//        CrashReport.testJavaCrash();
        // 用户输入有效性验证
        if (!checkInput(username, password, mSwitchLogin)) {
            return;
        }

        if (mSwitchLogin) {
            // 短信登录
            loginSMS(username, password);
        } else {
            // 账号密码登录
            login(username, password);
        }
    }

    /**
     * 短信验证码登录
     */
    public void sendSMS(String username) {
        if (IS_DEBUG_DATA) {
            onCountDown();
        } else {
            // 执行登录操作
            mModel.sendSMS(username)
                    .compose(RxUtils.applySchedulers(mRootView))                               // 切换线程
                    .subscribe(new ErrorHandleSubscriber<CommonResponse>(mErrorHandler) {
                        @Override
                        public void onError(Throwable t) {
                            super.onError(t);

                            mRootView.onDisableClick();
                        }

                        @Override
                        public void onNext(CommonResponse loginResponse) {
                            onCountDown();
                        }
                    });
        }
    }


    /**
     * 倒计时
     */
    private void onCountDown() {
        // 验证码已经发送成功，所以“下一步”可以点击了
        mRootView.onEnableClick();

        // 开始做倒计时效果
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(mobileCheckCodeTime + 1)                                                      // 超过多少秒停止执行
                .map(aLong -> {
                    return mobileCheckCodeTime - aLong;                                             // 由于是倒计时，需要将倒计时的数字反过来
                })
                .observeOn(AndroidSchedulers.mainThread())                                          // 切换线程
                .doOnSubscribe(disposable -> {
                    // 在执行的过程中按钮不可以点击
                    mRootView.onDisableSendVerificationCodeButton();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))                               // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long num) {
                        // 显示倒计时
                        mRootView.setCountDownTips(num + "s");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        // 在执行完毕后按钮才可以点击
                        mRootView.onEnableSendVerificationCodeButton();
                    }
                });
    }

    /**
     * 账号密码登录
     */
    private void login(String username, String password) {

        if (IS_DEBUG_DATA) {
            accountManager.saveAccountInfo(username, password, new LoginResponse("2025-08-30 00:02:00", new AccountInfo(
                    "1", "杨津", "1", "y423b4445071644a527a", "3941ca9ac15f3390f6c1511b8373b1e7", "0", "", "", "12335",
                    "15081865467", "33", "2025-05-10 09:18:54", "2025-05-10 09:18:54", "1", "2025-05-10 09:18:54",
                    "", "0", "0", "2", "CCU", "CCU", "朝阳院区", "1", -1
            ), 30, "9cab820ea9c7f3c03f161fe0fcf1b90c"));
            mRootView.jumbToMain();
        } else {
            // 执行登录操作
            mModel.toLogin(username, password)
                    .compose(RxUtils.applySchedulers(mRootView))                               // 切换线程
                    .subscribe(new ErrorHandleSubscriber<LoginResponse>(mErrorHandler) {
                        @Override
                        public void onNext(LoginResponse loginResponse) {
                            if (loginResponse != null) {
                                accountManager.saveAccountInfo(username, password, loginResponse);
                            }
                            accountManager.setLoginMethod(0);
                            mRootView.jumbToMain();
                        }
                    });
        }
    }


    /**
     * 短信登录
     */
    private void loginSMS(String username, String code) {

        if (IS_DEBUG_DATA) {
            accountManager.saveAccountInfo(username, "", new LoginResponse("2025-08-30 00:02:00", new AccountInfo(
                    "1", "杨津", "1", "y423b4445071644a527a", "3941ca9ac15f3390f6c1511b8373b1e7", "0", "", "", "12335",
                    "15081865467", "33", "2025-05-10 09:18:54", "2025-05-10 09:18:54", "1", "2025-05-10 09:18:54",
                    "", "0", "0", "2", "CCU", "CCU", "朝阳院区", "1", -1
            ), 30, "9cab820ea9c7f3c03f161fe0fcf1b90c"));
            mRootView.jumbToMain();
        } else {
            // 执行登录操作
            mModel.quickLogin(username, code)
                    .compose(RxUtils.applySchedulers(mRootView))                               // 切换线程
                    .subscribe(new ErrorHandleSubscriber<LoginResponse>(mErrorHandler) {
                        @Override
                        public void onNext(LoginResponse loginResponse) {
                            if (loginResponse != null) {
                                accountManager.saveAccountInfo(username, "", loginResponse);
                            }

                            accountManager.setLoginMethod(1);

                            mRootView.jumbToMain();
                        }
                    });
        }
    }


    /**
     * 用户输入有效性验证
     *
     * @return 校验是否通过
     */
    private boolean checkInput(String username, String password, boolean mSwitchLogin) {
        // 用户名和密码不能为空，为空时返回false同时给出提示。

        if (mSwitchLogin) {
            // 短信登录
            if ("".equals(username)) {
                mRootView.showMessage("请输入手机号");
                return false;
            }

            if (!RegexUtils.isMobileSimple(username)) {
                mRootView.showMessage(ArmsUtils.getString(mRootView.getActivity(), R.string.loginactivity_login_usercodenotnull));
                return false;
            }

            if ("".equals(password)) {
                mRootView.showMessage("请输入验证码");
                return false;
            }
        } else {
            // 密码登录
            if ("".equals(username)) {
                mRootView.showMessage("请输入用户名/手机号");
                return false;
            }

            if ("".equals(password)) {
                mRootView.showMessage(ArmsUtils.getString(mRootView.getActivity(), R.string.loginactitivy_password_title));
                return false;
            }
            if (password.length() < 6 || password.length() > 20) {
                mRootView.showMessage(ArmsUtils.getString(mRootView.getActivity(), R.string.loginactivity_login_pwderror));
                return false;
            }
        }
        return true;
    }

    /**
     * APP升级更新
     */
    private void checkUpdateManager() {
        if (IS_DEBUG_DATA) {
            AppUpdate appUpdate = new AppUpdate(112, "1.1.2", "小的来了", "小的来了.apk", "http:\\/\\/buypb.e1.luyouxia.net:28708\\/imgs\\/update\\/recycleapp-debug-1.1.2.apk", 0, 18, "1.更新了好多东西\n1.更新了好多东西\n1.更新了好多东西");
            if (haveNew(appUpdate)) {
                // 先提醒升级
                mRootView.askDialog(appUpdate);
            }
        } else {
            mModel.getVersion("android")
                    .compose(RxUtils.applySchedulers(mRootView, true, true))                                            // 切换线程
                    .subscribe(new ErrorHandleSubscriber<AppUpdate>(mErrorHandler) {
                        @Override
                        public void onError(Throwable t) {
                            // 不做任何处理
                        }

                        @Override
                        public void onNext(AppUpdate au) {
                            if (haveNew(au)) {
                                // 先提醒升级
                                mRootView.askDialog(au);
                            }
                        }
                    });
        }
    }

    /**
     * 版本号比较
     *
     * @return 是否升级
     */
    private boolean haveNew(AppUpdate appUpdate) {
        boolean haveNew = false;
        if (appUpdate == null) {
            return false;
        }

        int curVersionCode = DeviceUtils.getVersionCode(mRootView.getActivity().getApplicationContext());
        if (curVersionCode < appUpdate.getVerCode()) {
            haveNew = true;
        }
        return haveNew;
    }

    /**
     * 关闭APP时关闭定位
     */
    public void stopLocationService() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
    }
}
